<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-01-12 14:39:08
 * @Last Modified time: 2023-02-23 11:26:39
 */
namespace app\common\services\user;

use frank\base\BaseService;
use app\common\dao\user\UserDao;
use frank\exception\CommonException;
use frank\services\JwtAuthService;
use frank\utils\helper\StringHelper;

use app\common\services\user\UserWaterService;
use app\common\enum\user\WaterSourceEnum;

/**
 * 用户
 * Class UserService
 */
class UserService extends BaseService
{
    /**
     * UserService constructor.
     * @param UserDao $dao
     */
    public function __construct(UserDao $dao)
    {
        $this->dao = $dao;
    }

    public function getUserDetail($filter)
    {
        $detail = $this->dao->search($filter)
        ->with(['group'])
        ->withSum(['order' => function($query, &$alias) {
            $query->where('pay_status',1);
            $alias = 'order_pay_sum';
        }],'pay_price')
        ->withCount(['order' => function($query, &$alias) {
            $query->where('pay_status',1);
            $alias = 'order_count';
        }])
        ->find();
        if (!$detail) {
            throw new CommonException('用户不存在');
        }
        return $detail->toArray();
    }

    public function getDetail($filter,array $with = ['wechat','group'])
    {
        $detail = $this->dao->search($filter)->with($with)->find();
        if (!$detail) {
            throw new CommonException('用户不存在');
        }
        return $detail->toArray();
    }

    public function login($userId = 0,$appType){
        $user = $this->getDetail([
            'id'=>$userId
        ]);

        $tokenInfo = JwtAuthService::instance()->createToken((int)$userId,$appType);
        $exp =  $tokenInfo['params']['exp'];
        return [
            'token' => $tokenInfo['token'],
            'exp' => $exp,
            'user' => $user,
            'appType' => $appType
        ];
    }

    /**
     * 获取用户列表
     */
    public function getUserList(array $params)
    {
        [$page, $limit] = $this->getPageValue();
        $where = [];
        $list = $this->dao->getUserList($where, $page, $limit,[
            'group'
        ]);
        return $list;
    }

    /**
     * 用户充值：余额
     */
    public function rechargeToBalance($data,$id,$adminId = 0,$adminName = '')
    {
        if (!isset($data['money']) || $data['money'] === '' || $data['money'] < 0) {
            $this->error = '请输入正确的金额';
            return false;
        }
        $user = $this->dao->search(['id'=>$id])->find();
        // 判断充值方式，计算最终金额
        if ($data['mode'] === 'inc') {
            $mode = '增加';
            $diffMoney = $data['money'];
        } elseif ($data['mode'] === 'dec') {
            $mode = '减少';
            $diffMoney = -$data['money'];
        } else {
            $mode = '修改';
            $diffMoney = StringHelper::bcsub($data['money'], $user['balance']);
        }
        $userBalance = $user['balance'];
        // 更新记录
        $this->transaction(function () use ($data,$id,$userBalance,$mode, $diffMoney, $adminId,$adminName) {
            // 更新账户余额
            $this->dao->search(['id'=>$id])->inc('balance', (float)$diffMoney)->save();
            // // 新增余额变动记录
            UserWaterService::instance()->createWater(WaterSourceEnum::ADMIN, [
                'user_id' => $id,
                'money' => $diffMoney,
                'remark' => $data['remark'],
                'source_id' => $adminId,
                'user_balance' => $userBalance,
            ], [$adminName,$mode]);
        });
        return true;
    }

    
    /**
     * 获取新增加会员数量
     */
    public function getCreateTotal($day = null)
    {
        $filter = [];
        if (!is_null($day) && !is_null($day)) {
            $filter['create_time'] = [strtotime($day),strtotime($day) + 86400];
        }
        return number_format($this->dao->search($filter)->count());
    }

}
